package cn.tedu.tcc;

import cn.tedu.entity.Storage;
import cn.tedu.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Component
public class StroageTccAutionImpl implements StroageTccAution {

    @Autowired
    private StorageMapper stroageMapper;

    @Override
    @Transactional
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        Storage stroage = stroageMapper.findByProductId(productId);
        if (stroage.getResidue()<count){
            throw new RuntimeException("库存不足");
        }
        stroageMapper.updateResidueToFrozen(productId, count);
        // 第一阶段成功,添加标记
        ResultHolder.setResult(StroageTccAution.class, ctx.getXid(), "p");
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext ctx) {
        //二阶段执行之前,判断如果没有标记,则不执行二阶段操作
        if (ResultHolder.getResult(StroageTccAution.class,ctx.getXid()) == null){
            return true;
        }
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        stroageMapper.updateFrozenToUsed(productId,count);
        //第二阶段完成时,删除标记
        ResultHolder.removeResult(StroageTccAution.class,ctx.getXid());
        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext ctx) {
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        stroageMapper.updateFrozenToResidue(productId,count);
        return true;
    }
}
